package com.open.center.common.databind;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import com.open.center.common.constant.Enumerator;
import com.open.center.common.exception.OpenException;

/**
 * 枚举序列化
 * 与 @JsonValue 冲突，二者只能使用其一
 */
@Slf4j
public class JsonEnumSerializer extends JsonSerializer<Enumerator<?, Object>> {

    @Override
    public void serialize(Enumerator enumerator, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
        try {
            Object id = enumerator.getId();
            String name = enumerator.getName();

            Map<String, Object> mapJson = new HashMap<>();
            mapJson.put("id", id);
            mapJson.put("name", name);
            serializerProvider.defaultSerializeValue(mapJson, jsonGenerator);
        } catch (Exception e) {
            log.error("JsonEnumSerializer serialize error: {}", e.getMessage());
            throw new OpenException(e.getMessage());
        }
    }
}
